#include "StatisticsHandler.h"
#include "SimulationParameters.h"
#include <fstream>
using namespace std;
StatisticsHandler::StatisticsHandler(void)
{
	_cacheHits = _flashCacheHits = _totalIOs = 0;
	_extents = new map<string,int>();
}


StatisticsHandler::~StatisticsHandler(void)
{
	delete _extents;
}


void StatisticsHandler::reset(double time)
{
	// print to file statistics
	static bool first = true;
	if (first)
	{
		ofstream f(SimulationParameters::OutputDirectory + "cacheTypesHitRatio.csv");
		f << ",Cache Hits,Flash Hits,Total IOs, Cache ratio, Flash Ratio, Miss Ratio,Hit Ratio" << endl;
		f.close();
		first = false;
	}
	double cacheRatio = _cacheHits / _totalIOs;
	double flashRatio = _flashCacheHits / _totalIOs;
	double missRatio = (_totalIOs -  (_flashCacheHits + _cacheHits))/ _totalIOs;
	double hitRatio = 1-missRatio;
	ofstream f(SimulationParameters::OutputDirectory + "cacheTypesHitRatio.csv", ios::app);
	f << time << "," << _cacheHits << "," << _flashCacheHits << "," << _totalIOs << "," << cacheRatio << "," << flashRatio << "," << missRatio << "," << hitRatio << endl;
	f.close();
	// reset variables
	_cacheHits = _flashCacheHits = _totalIOs = 0;
}
void StatisticsHandler::cacheHit()
{
	_cacheHits++;
	_totalIOs++;
}
void StatisticsHandler::flashCacheHit()
{                         
	_flashCacheHits++;
	_totalIOs++;
}
void StatisticsHandler::miss()
{
	_totalIOs++;
}

map<string,int>* StatisticsHandler::getExtentsHistogram()
{
	return _extents;
}
void StatisticsHandler::extentFetch(std::string extentID)
{
	if (_extents->find(extentID) == _extents->end()) // first time found this extent
		_extents->insert(make_pair(extentID,1));
	else 
		_extents->at(extentID)++;
}
void StatisticsHandler::clearExtentsHistogram()
{
	_extents->clear();
}